package com.test.springboot.utils;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    /**
     * 共有5个车位
     * @param args
     */
    private static int MAX_AVAILABLE = 5;

    public static void main(String[] args) {

        /**
         * 最多5辆车停
         */
        Semaphore semaphore = new Semaphore(MAX_AVAILABLE);
        //共有10辆车
        for (int i = 1; i <= 10; i++) {
            new Park(semaphore,i).start();

        }
    }
    static class Park extends Thread {
        private Semaphore semaphore;
        private int num;

        public Park(Semaphore semaphore,int num) {
            this.semaphore = semaphore;
            this.num = num;
        }
        @Override
        public void run() {
            try {
                //拿到入场许可，驶入。
                semaphore.acquire();
                System.out.println("第"+num+"驶入停车场");
                Thread.sleep(2000);
                //驶出，释放入场许可。
                semaphore.release();
                System.out.println("第"+num+"驶出停车场");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}
